package com.atguigu.c_designed.m3beheviorModel.b5Observer;

import java.util.Observable;
import java.util.Observer;

public class ObserverClient {
    public static void main(String[] args) {
        GPer gper = GPer.getInstance();
        Teacher teacher1 = new Teacher("tom");
        Teacher teacher2 = new Teacher("jerry");
        gper.addObserver(teacher1);
        gper.addObserver(teacher2);

        Question question = new Question();
        question.setUserName("张三");
        question.setContent("观察者模式适用于哪些场景？");
        gper.publishQuestion(question);


    }
}

class Question{
    private String userName;
    private String content;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

class GPer extends Observable {
    private String name = "GPer生态圈";
    private static final GPer gper = new GPer();

    private GPer() {}

    public static GPer getInstance(){
        return gper;
    }

    public String getName() {
        return name;
    }
    public void publishQuestion(Question question){
        System.out.println(question.getUserName() + "在" + this.name + "上提交了一个问题。");
        setChanged();
        notifyObservers(question);
    }
}

class Teacher implements Observer {
    private String name;
    public Teacher(String name) {
        this.name = name;
    }

    @Override
    public void update(Observable o, Object arg) {
        GPer gper = (GPer)o;
        Question question = (Question)arg;
        System.out.println("======================");
        System.out.println(name + "老师，你好！\n" +
                "您收到了一个来自" + gper.getName() + "的提问，希望您解答。问题内容如下：\n" +
                question.getContent() + "\n" +
                "提问者：" + question.getUserName());
    }
}